// pages/address/addAddress/addAddress.js
const app = getApp()
import {
  postRequest,
  getRequest,
  postParamsRequest
} from '../../../api/request';
import {
  showTips,
  showModal,
  trim,
  trim2,
} from '../../../utils/util.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeColor: app.globalData.themeColor,
    subColor: app.globalData.subColor,
    btnColor: app.globalData.btnColor,
    label: "",
    id: 0,
    addressName: "",
    address: "",
    latitude: "",
    longitude: "",
    province: "",
    city: "",
    area: "",
    address_all: null,
    mobile: "",
    real_name: "",
    genderList: [{
        id: 1,
        name: "先生",
        checked: true,
      },
      {
        id: 2,
        name: "女士",
        checked: false,
      },
    ],
    gender: "先生",
    isDefault: 0,
    //提交锁
    submitLock: false,
    //等待加载
    loadModal: false,
  },
  //选择标签
  selectTag(e) {
    if (e.currentTarget.dataset.label == this.data.label) {
      this.setData({
        label: ""
      })
    } else {
      this.setData({
        label: e.currentTarget.dataset.label
      })
    }

  },
  //性别单选框改变时
  radioChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)

    const items = this.data.genderList
    for (let i = 0, len = items.length; i < len; ++i) {
      items[i].checked = items[i].id == e.detail.value;
      if (items[i].checked) {
        this.setData({
          gender: items[i].name,
        });
      }
    }
    this.setData({
      genderList: items
    })
  },
  //点击性别文字
  genderChange(e){
    const items = this.data.genderList;
    for (let i = 0, len = items.length; i < len; ++i) {
      items[i].checked = items[i].id == e.currentTarget.dataset.id;
      if (items[i].checked) {
        this.setData({
          gender: items[i].name,
        });
      }
    }
    this.setData({
      genderList: items
    })
  },
  //手机号码自动填写
  getPhoneNumber(e) {
    console.log(e);
    if (e.detail.errMsg != 'getPhoneNumber:ok') {
      return
    }
    let param = {
      iv: e.detail.iv,
      encryptedData: e.detail.encryptedData,
      memberId: app.myInfo.memberId,
    };
    postParamsRequest("/api/vip/getPhoneNumber", param).then((res) => {
      console.log(res);
      let data = res.data.data
      if (data.phoneNumber) {
        this.setData({
          mobile: data.phoneNumber
        })
      }
    }).catch((err) => {});
  },
  //地址自动填写
  chooseLocation(e) {
    let that = this
    wx.showLoading();
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      highAccuracyExpireTime: 3001,
      success(res) {
        console.log(res);
        wx.hideLoading();
        const latitude = res.latitude
        const longitude = res.longitude
        const speed = res.speed
        const accuracy = res.accuracy
        wx.chooseLocation({
          latitude: latitude,
          longitude: longitude,
          success(res) {
            console.log(res);
            if (res != null) {
              var add = res.address;
              var reg = /.+?(省|市|自治区|自治州|县|区)/g;
              let latitude = res.latitude,
                longitude = res.longitude;
              let addArray = add.match(reg);
              let province = '',
                city = '',
                area = '',
                address = ''
              if (addArray.length == 2) {
                province = '',
                  city = addArray[0],
                  area = addArray[1]
              } else {
                province = addArray[0],
                  city = addArray[1],
                  area = addArray[2]
              }
              // let province = addArray[0],
              //   city = addArray[1],
              //   area = addArray[2],
              //   address = '',

              if (area != undefined) {
                address = add.split(area.charAt(area.length - 1))[1]
              }
              that.setData({
                addressName: res.name,
                address: address,
                latitude: latitude,
                province: province,
                longitude: longitude,
                city: city,
                area: area,
                address_all: add,
              })
              console.log(that.data);
            } else {
              wx.showToast({
                title: '请选择地址',
                icon: 'none',
                duration: 2000
              })
              that.setData({
                address_all: null
              })
            }
          },
          fail(res) {
            console.log(res);
          }
        })
      },
      fail(error) {
        console.log(error);
        showModal({
          title: '警告',
          content: '您已拒接获取位置信息,您需要允许授权才能获取当前地址',
          showCancel: true
        }).then(res => {
          console.log(res);
          // nav({
          //   url: '/pages/personalNew/personalNew'
          // })

          wx.openSetting({
            success: function (res2) {
              console.log(res2);
              wx.getLocation({
                type: 'gcj02',
                success: function (res2) {

                },
              })
            }
          })

        }).catch(_ => {
          console.log('获取位置失败')

        })
      }
    })
  },
  //收货人改变时
  changeRealName(e) {
    this.setData({
      real_name: e.detail.value
    })
  },
  //手机号
  changeMobile(e) {
    this.setData({
      mobile: trim2(e.detail.value)
    })
  },
  //门牌号
  changeAddress(e) {
    this.setData({
      address: e.detail.value
    })
  },

  //是否默认地址
  defaultAddChange(e) {
    this.setData({
      isDefault: e.detail.value ? 1 : 0,
    })
  },

  //保存地址
  saveAddress() {
    if (this.data.submitLock) {
      return
    }
    if (this.data.real_name == '') {
      showTips('收货人姓名不能为空', 'none')
      return
    }
    this.setData({
      mobile: trim2(this.data.mobile)
    })
    console.log(this.data.mobile);
    if (this.data.mobile == '' || this.data.mobile.length != 11) {
      showTips('请正确输入手机号码', 'none')
      return
    }
    if (this.data.address_all == '' || this.data.address_all == null || this.data.latitude == null || this.data.longitude == null) {
      showTips('请选择地址', 'none')
      return
    }
    let lnglat = this.data.longitude + "," + this.data.latitude;
    let param = {
      id: this.data.id,
      realName: this.data.real_name,
      addressName: this.data.addressName,
      address: this.data.address,
      province: this.data.province == '' || !this.data.province ? this.data.city : this.data.province,
      city: this.data.city,
      area: this.data.area,
      mobile: this.data.mobile,
      label: this.data.label,
      beid: app.beid,
      memberId: app.myInfo.memberId,
      gender: this.data.gender,
      isDefault: this.data.isDefault,
      lnglat: lnglat,
    };
    console.log(param);

    this.setData({
      submitLock: true
    })

    postRequest("/api/vip/member/saveMemberAddress", param).then((res) => {
      console.log(res);
      wx.showToast({
        title: '保存成功',
        icon: 'none',
      })
      this.setData({
        submitLock: false
      })
      wx.navigateBack();
    }).catch((err) => {
      this.setData({
        submitLock: false
      })
    });

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this;
    //编辑页面
    if (options.id != undefined) {
      wx.showLoading({
        title: '加载中...',
      })
      getRequest("/api/vip/member/getMemberAddressDetail", {
        id: options.id,
        memberId: app.myInfo.memberId,
      }).then((res) => {
        console.log(res.data.data);
        let result = res.data.data;
        //性别
        const items = this.data.genderList;
        for (let i = 0, len = items.length; i < len; ++i) {
          items[i].checked = items[i].name == result.gender;
          if (items[i].checked) {
            this.setData({
              gender: items[i].name,
            });
          }
        }
        that.setData({
          id: result.id,
          real_name: result.realName,
          addressName: result.addressName,
          mobile: result.mobile,
          address: result.address,
          latitude: result.lnglat.split(',')[1], //todo 
          longitude: result.lnglat.split(',')[0],
          address_all: result.province + result.city + result.area + result.address,
          province: result.province,
          city: result.city,
          area: result.area,
          label: result.label,
          isDefault: result.isDefault,
          genderList: items,
        })
        wx.hideLoading();
      }).catch((err) => {});
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})